import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_edit_callback_widget/common_edit_callback_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_list_page_widget/common_list_page_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_title_edit_with_underline_widget/typeof/common_title_edit_with_underline_typeof.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/bean/project_response_bean.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_http_lib.dart';

import 'bean/user_select_sort_save_response_bean.dart';

class ProjectWidget extends StatefulWidget {
  final String selectedId;
  final String projectType;
  const ProjectWidget({Key key, this.selectedId, this.projectType="01"}) : super(key: key);
  @override
  _ProjectWidgetState createState() => _ProjectWidgetState();

  ///跳转方法
  static Future<EditTextAndValue> navigatorPush(
      BuildContext context, String selectedId) {
    return RouterUtils.routeForFutureResult<EditTextAndValue>(
      context,
      ProjectWidget(
        selectedId: selectedId,
      ),
    );
  }
}

class _ProjectWidgetState extends State<ProjectWidget> {
  bool isLightUp = false;//确认按钮是否亮起
  String mProjectText;//项目文本
  String selectedId;//选中的行ID
  CommonListPageWidgetState<ProjectListItemBean, ProjectResponseBean>
  _mState;

  void setCommonListState(
      CommonListPageWidgetState<ProjectListItemBean, ProjectResponseBean>
      state) {
    _mState = state;
  }

  @override
  //初始化
  void initState() {
    // TODO: implement initState
    super.initState();
    selectedId = widget.selectedId;
  }
  @override
  Widget build(BuildContext context) {
    return CustomAnnotatedRegion(
       Scaffold(
        // resizeToAvoidBottomInset: false,
        // resizeToAvoidBottomPadding: false,
        backgroundColor: Color(0xFF191E31),
        body: CommonPackUpKeyboardWidget(
          child: Column(
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              _toTopBarWidget(),
              _searchDepartmentWidget(),
              //下划线
              Container(
                height: 1,
                padding: const EdgeInsets.only(left: 21,),
                child: Divider(
                  height: 1.0,
                  indent: 0.0,
                  color: Color(0xFF303546),
                ),
              ),
              SizedBox(
                height: 10,
              ),
              Expanded(
                child: _toCustomListWidget(),
              ),
            ],
          ),
        ),
      ),
      navigationBarColor: Color(0xFF191E31),
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "项目",
      rightWidget: _buttonWidget(),
    );
  }

  Widget _buttonWidget() {
    return Container(
      child: CommonFixedHeightConfirmButtonWidget(
        isAlive: isLightUp,
        width: 48,
        height: 24,
        unSelectBgColor:
        ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
        selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        unSelectTextStyle: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 12,
            fontWeight: FontWeight.w600),
        selectedTextStyle: TextStyle(
            color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
        text: "确定",
        onTap: () {
          //提交按钮
          if(isLightUp){
            _httpSave();
          }
        },
      ),
    );
  }

  void _httpSave() {
    if (mProjectText == null || mProjectText.isEmpty) {
      VgToastUtils.toast(context, "请输入项目名称");
      return;
    }
    List<ProjectListItemBean> projectList = _mState?.data;
    if (projectList == null || projectList.isEmpty) {
      _saveDepartmentNameHttp();
      return;
    }
    for (ProjectListItemBean item in projectList) {
      if (item?.name == mProjectText) {
        _pop(item);
        return;
      }
    }
    _saveDepartmentNameHttp();
  }

  ///返回部门选中值
  void _pop(ProjectListItemBean itemBean) {
    if (itemBean == null) {
      return;
    }
    RouterUtils.pop(context,
        result: EditTextAndValue(value: itemBean.id, editText: itemBean.name));
  }

  ///保存接口
  void _saveDepartmentNameHttp() {
    if (mProjectText == null || mProjectText.isEmpty) {
      VgToastUtils.toast(context, "项目名称不能为空");
      return;
    }
    VgHudUtils.show(context,"保存中");
    VgHttpUtils.post(ServerApi.BASE_URL + "app/appAddChooseInfo", params: {
      "authId" : UserRepository.getInstance().authId ?? "",
      "name" : mProjectText.trim() ?? "",
      "type": widget.projectType,
    },callback: BaseCallback(
        onSuccess: (dynamic val){
          VgHudUtils.hide(context);
          if(val == null){
            return;
          }
          UserSelectSortSaveResponseBean successBean = UserSelectSortSaveResponseBean.fromMap(val);
          if(successBean == null || successBean.data == null ||successBean.data.isEmpty){
            VgToastUtils.toast(context, "项目添加返回值错误");
            return;
          }
          ProjectListItemBean projectListItemBean = new ProjectListItemBean();
          // projectListItemBean.id = successBean.data;
          // projectListItemBean.name = mProjectText;
          // _pop(projectListItemBean);
          successBean.data.forEach((element) {
            if(element?.name!=null && element?.name!="" && element?.name==mProjectText){
              projectListItemBean.id =  element.id;
            }
          });
          projectListItemBean.name = mProjectText;
          _pop(projectListItemBean);
          // _pop(ProjectListItemBean()..id = successBean.data..name = mProjectText);
          // _pop(DepartmentListItemBean()..id = successBean.data..name = mDepartmentText);
        },
        onError: (String msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }
    ));
  }

  Widget _searchDepartmentWidget() {
    return Container(
      height: 50,
      color: Color(0xFF3A3F50),
      child: CommonEditCallbackWidget(
        hintText: "请输入项目名称",
        onChanged: (String projectText) {
          mProjectText=projectText;
          if (projectText == null || projectText == "" || projectText.trim().isEmpty)
            isLightUp = false;
          else
            isLightUp = true;
          setState(() {});
        },
        onSubmitted: (String projectText) {
          mProjectText=projectText;
          if (projectText == null || projectText == "" || projectText.trim().isEmpty)
            isLightUp = false;
          else
            isLightUp = true;
          setState(() {});
        },
      ),
    );
  }

  //封装的列表
  Widget _toCustomListWidget() {
    return CommonListPageWidget<ProjectListItemBean, ProjectResponseBean>(
      enablePullUp: false,
      enablePullDown: false,
      queryMapFunc:(int page) => {
        "authId": UserRepository.getInstance().authId ?? "",
        "name":"",
        "type": widget.projectType,
      },
      parseDataFunc: (VgHttpResponse resp) {
        ProjectResponseBean bean =
        ProjectResponseBean.fromMap(resp?.data);
        return bean;
      },
      itemBuilder:
          (BuildContext context, int index, ProjectListItemBean itemBean) {
        return _toListItemWidget(context, index, itemBean);
      },
      //分割器构造器
      separatorBuilder: (context, int index, _) {
        return Container(
          height: 0.5,
          color: ThemeRepository.getInstance().getCardBgColor_21263C(),
          padding: const EdgeInsets.only(left: 15),
          child: Container(
            color: Color(0xFF303546),
          ),
        );
        // return divider;
      },
      netUrl:ServerApi.BASE_URL + "app/appChooseInfo",
      httpType: VgHttpType.post,
      stateFunc: (CommonListPageWidgetState<ProjectListItemBean,
          ProjectResponseBean>
      state) {
        _mState = state;
      },
    );
  }

  Widget _toListItemWidget(
      BuildContext context, int index, ProjectListItemBean itemBean) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        //判断字体是否选中
        selectedId = itemBean.id;
        setState(() {});
        //收键盘方法
        // FocusScope.of(context).requestFocus(FocusNode());
        VgToolUtils.removeAllFocus(context);
        //延迟执行
        Future.delayed(Duration(milliseconds: 10), () {
          RouterUtils.pop(context,
              result: EditTextAndValue(
                editText: itemBean.name,
                value: itemBean.id,
              ));
        });
      },
      child: Container(
        color: Color(0xFF21263C),
        height: 50,
        alignment: Alignment.centerLeft,
        padding: const EdgeInsets.symmetric(horizontal: 15),
        child: Text(
          itemBean?.name ?? "",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: itemBean.id != selectedId
                ? Color(0xFFD0E0F7)
                : Color(0xFF1890FF),
            fontSize: 14,
          ),
        ),
      ),
    );
  }
}
